﻿using Furion.DatabaseAccessor;
using iWare.Wms.WorkerService.ThirdDB;
using Yitter.IdGenerator;

namespace iWare.Wms.WorkerService
{
    public class SupplierInfoERP : BackgroundService
    {
        private readonly ILogger<SupplierInfoERP> _logger;
        // 服务工厂
        private readonly IServiceScopeFactory _scopeFactory;

        public SupplierInfoERP(ILogger<SupplierInfoERP> logger,
                      IServiceScopeFactory scopeFactory)
        {
            _logger = logger;
            _scopeFactory = scopeFactory;
        }

        // 启动
        public override Task StartAsync(CancellationToken cancellationToken)
        {
            return base.StartAsync(cancellationToken);
        }

        // 执行逻辑
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                //每天凌晨定时同步供应商基本信息
                await AddSupplierInfo();

                await Task.Delay(24 * 60 * 60 * 1000, stoppingToken);
            }
        }

        #region 每天凌晨定时同步供应商基本信息
        /// <summary>
        /// 每天凌晨定时同步供应商基本信息
        /// </summary>
        /// <returns></returns>
        public async Task AddSupplierInfo()
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var services = scope.ServiceProvider;
                var respository = Db.GetSqlRepository<ERPDbContextLocator>();

                //获取仓储实体
                var _supplierInfoRep = Db.GetRepository<SupplierInfo>(services);
                var _sysUserRep = Db.GetRepository<SysUser>(services);
                var _sysUserRoleRep = Db.GetRepository<SysUserRole>(services);

                var whereTime = DateTime.Now.AddMonths(-1).ToString("yyyyMMdd");
                var supplierInfoList = await respository
                    .SqlQueryAsync<SupplierInfoErpInput>
                    (@"select MA001, --供应商编号
	                          MA002, --简称
	                          MA003, --公司全称
	                          MA008, --TEL(一)
	                          MA012, --负责人
	                          MA013, --联系人（一）
	                          MA014, --联系地址（一）
                              MA022  --创建时间
                       from PURMA where MA022>'" + whereTime + "' order by MA022 desc");

                var addSupplierInfoList = new List<SupplierInfo>();

                foreach (var item in supplierInfoList)
                {
                    var isExists = await _supplierInfoRep.AnyAsync(u => u.Code.Equals(item.MA001));

                    string code = item.MA001 == null ? "" : item.MA001.Trim(); //账号
                                                                               //不存在执行新增操作
                    if (!isExists)
                    {
                        var addSupplierInfoModel = new SupplierInfo
                        {
                            Id = YitIdHelper.NextId(),
                            Code = item.MA001 == null ? "" : item.MA001.Trim(),
                            AbbreviationName = item.MA002 == null ? "" : item.MA002.Trim(),
                            Name = item.MA003 == null ? "" : item.MA003.Trim(),
                            Tel = item.MA008 == null ? "" : item.MA008.Trim(),
                            LeadingCadre = item.MA012 == null ? "" : item.MA012.Trim(),
                            Contacts = item.MA013 == null ? "" : item.MA013.Trim(),
                            ContactAddress = item.MA014 == null ? "" : item.MA014.Trim(),
                            CreatedUserName = "LES SYSTEM",
                            CreatedTime = DateTimeOffset.Now
                        };
                        addSupplierInfoList.Add(addSupplierInfoModel);
                    }

                    var isExist = await _sysUserRep.AnyAsync(u => u.Account == code && !u.IsDeleted, false, true);
                    if (!isExist)
                    {
                        // 新增用户表信息
                        var user = new SysUser
                        {
                            Id = YitIdHelper.NextId(),
                            Account = item.MA001 == null ? "" : item.MA001.Trim(),
                            NickName = item.MA001 == null ? "" : item.MA001.Trim(),
                            Password = "e10adc3949ba59abbe56e057f20f883e",
                            Name = item.MA003 == null ? "" : item.MA003.Trim(),
                            AdminType = AdminType.Supplier,
                        };
                        await _sysUserRep.InsertNowAsync(user, true);

                        // 新增用户角色表信息
                        var sysUserRole = new SysUserRole
                        {
                            SysUserId = user.Id,
                            SysRoleId = 396085390729285
                        };
                        await _sysUserRoleRep.InsertNowAsync(sysUserRole);
                    }
                }

                // 批量新增
                await _supplierInfoRep.InsertNowAsync(addSupplierInfoList);

                Console.WriteLine("定时同步供应商基本信息");
            }
        }
        #endregion

        // 停止
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            return base.StopAsync(cancellationToken);
        }
    }
}
